//
//  ZRImageScrollView.m
//  HelpThePoor
//
//  Created by van7ish on 2017/1/11.
//  Copyright © 2017年 van7ish. All rights reserved.
//

#import "ZRImageScrollView.h"

#define maxZoomScale 2.5

@implementation ZRImageScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpViews];
    }
    return self;
}
- (void)setUpViews {
    
    self.backgroundColor = COLOR_WHITE;
    self.delegate = self;//一定要遵守代理
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    //设置最大放大倍数
    self.minimumZoomScale = 1.0;
    self.maximumZoomScale = maxZoomScale;
    //粘贴一张图片
    _imageView = [[UIImageView alloc] init];
    _imageView.frame = CGRectMake(0, 0, self.width, self.height);
//    _imageView.center = CGPointMake(SCREEN_W / 2, SCREEN_H / 2);
//    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    //添加双击事件
    _doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [_doubleTapGesture setNumberOfTapsRequired:2];
    [_imageView addGestureRecognizer:_doubleTapGesture];
    _imageView.userInteractionEnabled = YES;
    [self addSubview:_imageView];
}

//双指缩放代码
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

//双击定点放大代码
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
    CGFloat zoomScale = self.zoomScale;
    zoomScale = (zoomScale == 1.0) ? maxZoomScale : 1.0;
    CGRect zoomRect = [self zoomRectForScale:zoomScale withCenter:[gesture locationInView:gesture.view]];
    [self zoomToRect:zoomRect animated:YES];
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height =self.frame.size.height / scale;
    zoomRect.size.width  =self.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / maxZoomScale);
    zoomRect.origin.y = center.y - (zoomRect.size.height / maxZoomScale);
    return zoomRect;
}

@end
